<template>
  <el-dialog v-model="visible" :title="title" width="50%">
    <el-form :model="form">
      <el-form-item label="单位名称" :label-width="formLabelWidth">
        <el-input v-model="form.unitName" />
      </el-form-item>
      <el-form-item label="单位地址" :label-width="formLabelWidth">
        <el-input v-model="form.unitAddress" />
      </el-form-item>
      <el-form-item label="营业执照" :label-width="formLabelWidth">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8080/rbac/common/upload"
          :headers="headers"
          :show-file-list="false"
          :on-success="handleBusinessLicenseSuccess"
        >
          <img
            v-if="form.businessLicense"
            :src="imgSrc(form.businessLicense)"
            class="avatar"
            style="width: 100px; height: 100px;"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="统一社会信用代码" :label-width="formLabelWidth">
        <el-input v-model="form.creditCode" />
      </el-form-item>
      <el-form-item label="单位简介" :label-width="formLabelWidth">
        <el-input type="textarea" v-model="form.introduction" />
      </el-form-item>
      <el-form-item label="主营业务" :label-width="formLabelWidth">
        <el-input type="textarea" v-model="form.mainBusiness" />
      </el-form-item>
      <el-form-item label="注册时间" :label-width="formLabelWidth">
        <el-date-picker v-model="form.registrationTime" type="datetime" />
      </el-form-item>
      <el-form-item label="注册资金(万)" :label-width="formLabelWidth">
        <el-input-number v-model="form.registeredCapital" :precision="2" :step="0.1" />
      </el-form-item>
      <el-form-item label="入会申请表" :label-width="formLabelWidth">
        <el-upload
          class="file-uploader"
          action="http://localhost:8080/rbac/common/upload"
          :headers="headers"
          :on-success="handleApplicationFormSuccess"
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="form.applicationForm2"
          style="width: 100%;"
        >
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传一个文件</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="联系人姓名" :label-width="formLabelWidth">
        <el-input v-model="form.contactName" />
      </el-form-item>
      <el-form-item label="联系人电话" :label-width="formLabelWidth">
        <el-input v-model="form.contactPhone" />
      </el-form-item>
      <el-form-item label="联系人职务" :label-width="formLabelWidth">
        <el-input v-model="form.contactPosition" />
      </el-form-item>
      <el-form-item label="联系人邮箱" :label-width="formLabelWidth">
        <el-input v-model="form.contactEmail" />
      </el-form-item>
      <el-form-item label="入会时间" :label-width="formLabelWidth">
        <el-date-picker v-model="form.joinTime" type="date" />
      </el-form-item>
      <el-form-item label="会员到期时间" :label-width="formLabelWidth">
        <el-date-picker v-model="form.expireTime" type="date" />
      </el-form-item>
      <el-form-item label="小程序是否展示" :label-width="formLabelWidth">
        <el-switch v-model="form.showFlag" active-value="1" inactive-value="0" />
      </el-form-item>
      <el-form-item label="备注" :label-width="formLabelWidth">
        <el-input type="textarea" v-model="form.remarks" />
      </el-form-item>
      <el-form-item label="排序" :label-width="formLabelWidth">
        <el-input-number v-model="form.sort" :precision="2" :step="0.1" />
      </el-form-item>
      <el-form-item label="会员状态" :label-width="formLabelWidth">
        <el-select v-model="form.status" placeholder="请选择状态">
          <el-option label="已到期" :value="0" />
          <el-option label="正常" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="删除状态" :label-width="formLabelWidth">
        <el-switch v-model="form.delFlag" active-value="1" inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue"; // 引入 Plus 图标
import {instance} from "../request.js";

const visible = ref(false)
const formLabelWidth = '140px'
const title = ref('新增')
//上传相关
let headers = {
  token:sessionStorage.getItem('token')
}

// 表单默认值
let defaultForm = {
  id: '',
  openid: '',
  applyId: '',
  unitName: '',
  unitAddress: '',
  businessLicense: '',
  creditCode: '',
  introduction: '',
  mainBusiness: '',
  registrationTime: null,
  registeredCapital: null,
  applicationForm:'',
  applicationForm2: [],
  contactName: '',
  contactPhone: '',
  contactPosition: '',
  contactEmail: '',
  joinTime: null,
  expireTime: null,
  showFlag: '1',
  remarks: '',
  sort: null,
  status: 1,
  delFlag: '0'
}

let form = ref(defaultForm)

// 重置表单
function resetForm() {
  form.value = structuredClone(defaultForm)
}

// 根据id查询数据
async function getById(id: string) {
  try {
    let result = await instance.get('/bsMember/' + id)
    let { code, data, msg } = result.data
    if (code == 200) {
      return data
    }
    ElMessage({ message: msg, type: 'warning', })
  } catch (e) {
    console.log(e)
    ElMessage({ message: '查询数据失败', type: 'warning', })
  }
}

// 声明需要监听的父组件事件
const emit = defineEmits(['refresh'])

// 提交表单时转换数据
async function submitForm() {
  try {
    let result
    console.log("form.value.applicationForm2",form.value.applicationForm2)
    if (form.value.applicationForm2){
      form.value.applicationForm = form.value.applicationForm2.map((t:any)=>t.response.data).join(",")
    }
    if (form.value.id) {
      result = await instance.put('/bsMember', form.value)
    } else {
      result = await instance.post('/bsMember', form.value)
    }
    let { code, msg } = result.data
    if (code == 200) {
      ElMessage({ message: msg, type: 'success', })
      visible.value = false
      emit('refresh')
      return
    }
    ElMessage({ message: msg, type: 'warning', })
  } catch (e) {
    console.log(e)
    ElMessage({ message: '保存/更新数据失败', type: 'warning', })
  }
}

// add方法
function add() {
  resetForm()
  title.value = '新增'
  visible.value = true
}

// 编辑的方法
async function edit(row: any) {
  title.value = '编辑'
  visible.value = true
  form.value = await getById(row.id)
}

// 处理营业执照上传成功
function handleBusinessLicenseSuccess(response: any, uploadFile: any) {
  if (response.code === 200) {
    form.value.businessLicense = response.data;
    ElMessage({ message: "营业执照上传成功", type: "success" });
  } else {
    ElMessage({ message: "营业执照上传失败", type: "warning" });
  }
}

// 处理入会申请表上传成功
function handleApplicationFormSuccess(response: any, uploadFile: any) {
  if (response.code === 200) {
    if (!form.value.applicationForm2){
      form.value.applicationForm2 = []
    }
    form.value.applicationForm2.push(uploadFile); // 更新文件列表
    ElMessage({ message: "入会申请表上传成功", type: "success" });
  } else {
    ElMessage({ message: "入会申请表上传失败", type: "warning" });
  }
}

// 文件超出个数限制时的处理
function handleExceed(files: File[], fileList: File[]) {
  ElMessage.warning(`只能上传一个文件`);
}

let imgSrc = computed(() => {
  return (v:string)=>{
    //判断是否http/https开头
    if (v.startsWith('http://') || v.startsWith('https://')) {
      return v;
    }
    return v ? 'http://localhost:8080/rbac/common/download/' + v : '';
  }
});

// 暴露给外面使用
defineExpose({
  add,
  edit,
})
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  border: 1px dashed #ccc;
}

.file-uploader .el-upload {
  display: inline-block;
}
</style>